﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

using MessageUI;
using UIKit;

namespace Outcoder.LauncherModel.Launchers
{
	public class EmailComposeTask : LauncherBase, IEmailComposeLauncher
	{
		MFMailComposeViewController mailController;

		public string Subject { get; set; }

		public string Body { get; set; }

		readonly IList<string> toList = new List<string>();

		public IList<string> ToList
		{
			get
			{
				return toList;
			}
		}

		readonly IList<string> ccList = new List<string>();

		public IList<string> CCList
		{
			get
			{
				return ccList;
			}
		}

		/// <summary>
		/// This property is ignored in iOS.
		/// </summary>
		public int? CodePage { get; set; }

		public string MimeType { get; set; }
		public bool UseHtmlFormat { get; set; }

		readonly IList<string> bccList = new List<string>();

		public IList<string> BccList
		{
			get
			{
				return bccList;
			}
		}

		public bool CanSendMail
		{
			get
			{
				return MFMailComposeViewController.CanSendMail;
			}
		}

		public override Task<bool> ShowAsync()
		{
			mailController = new MFMailComposeViewController();

			if (toList.Any())
			{
				mailController.SetToRecipients(toList.ToArray());
			}

			if (!string.IsNullOrWhiteSpace(Subject))
			{
				mailController.SetSubject(Subject);
			}

			if (!string.IsNullOrWhiteSpace(Body))
			{
				mailController.SetMessageBody(Body, UseHtmlFormat);
			}

			mailController.Finished += HandleMailControllerFinished;

			var viewController = UIApplication.SharedApplication.Windows[0].RootViewController;
			viewController.PresentViewController(mailController, true, null);

			return Task.FromResult(true);
		}

		public event EventHandler<MFComposeResultEventArgs> SendMailFinished; 

		void HandleMailControllerFinished(object s, MFComposeResultEventArgs args)
		{
			args.Controller.DismissViewController(true, null);

			OnSendMailFinished(args);
		}

		protected virtual void OnSendMailFinished(MFComposeResultEventArgs args)
		{
			var temp = SendMailFinished;
			if (temp != null)
			{
				temp(this, args);
			}
		}
	}
}